import _slicedToArray from '@babel/runtime/helpers/esm/slicedToArray';
import _toConsumableArray from '@babel/runtime/helpers/esm/toConsumableArray';
import { useCallback, useEffect, useState } from 'react';
export default function useOther(_ref) {
  var options = _ref.options,
    value = _ref.value,
    onChange = _ref.onChange;
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    selectedValue = _useState2[0],
    setSelectedValue = _useState2[1];
  var _useState3 = useState(undefined),
    _useState4 = _slicedToArray(_useState3, 2),
    otherValue = _useState4[0],
    setOtherValue = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    otherChecked = _useState6[0],
    setOtherChecked = _useState6[1];
  useEffect(
    function () {
      if (value) {
        var optionValues = options.map(function (option) {
          return option.value;
        });
        var selectedVal = [];
        var otherVal;
        value.forEach(function (val) {
          if (optionValues.includes(val)) {
            selectedVal.push(val);
          } else {
            otherVal = val;
          }
        });
        setSelectedValue(selectedVal);
        setOtherValue(otherVal);
        if (otherVal !== undefined) setOtherChecked(true);
      }
    },
    [value, options],
  );
  var changeSelectedValue = useCallback(
    function (vals) {
      setSelectedValue(vals);
      if (otherValue !== undefined) {
        if (onChange) onChange([].concat(_toConsumableArray(vals), [otherValue]));
      } else {
        if (onChange) onChange(_toConsumableArray(vals));
      }
    },
    [otherValue],
  );
  var changeOtherValue = useCallback(
    function (val) {
      setOtherValue(val);
      if (onChange)
        onChange(
          val !== undefined ? [].concat(_toConsumableArray(selectedValue), [val]) : selectedValue,
        );
    },
    [selectedValue],
  );
  var changeOtherChecked = useCallback(
    function (checked) {
      setOtherChecked(checked);
      if (!checked) changeOtherValue();
    },
    [changeOtherValue],
  );
  return {
    selectedValue: selectedValue,
    otherValue: otherValue,
    otherChecked: otherChecked,
    changeSelectedValue: changeSelectedValue,
    changeOtherValue: changeOtherValue,
    changeOtherChecked: changeOtherChecked,
  };
}
